#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <sys/sem.h>
 #include <sys/shm.h>


union semval
{
	int val;
};

int sem_init(int semid,int semnum,int val)
{
	union semval mysem;
	mysem.val=val;
	semctl(semid,semnum,SETVAL,mysem);

	return 0;
}

int sem_p(int semid,int semnum)
{
	struct sembuf mybuf;
	mybuf.sem_num=semnum;
	mybuf.sem_op=-1;
	mybuf.sem_flg=0;
	semop(semid,&mybuf,1);

	return 0;
}


int sem_v(int semid,int semnum)
{
	struct sembuf mybuf;
	mybuf.sem_num=semnum;
	mybuf.sem_op=1;
	mybuf.sem_flg=0;
	semop(semid,&mybuf,1);

	return 0;
}


int main(int argc, const char *argv[])
{
	key_t key1=ftok("./1.txt",'c');
	int semid=semget(key1,2,IPC_CREAT|0664);

	sem_init(semid,0,1);
	sem_init(semid,1,0);

	key_t key2=ftok("./1.txt",'d');
	int shmid=shmget(key2,1024,IPC_CREAT|0664);
	char *shareme=(char *)shmat(shmid,NULL,0);
	
	pid_t pid=fork();
	if(pid==0)
	{
		while(1)
		{
			sem_p(semid,0);
			printf("ziwrite\n");
			scanf("%s",shareme);
			sem_v(semid,1);
		}
	}
	else if(pid>0)
	{
		while(1)
		{
			sem_p(semid,1);
			printf("fuwrite\n");
			scanf("%s",shareme);
			sem_v(semid,0);
		}
	}


	return 0;
}
